package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.dao.ToolsDemandPlanDao;
import com.sugon.dao.ToolsDemandPlanItemDao;
import com.sugon.entity.SysDeptEntity;
import com.sugon.entity.SysUserEntity;
import com.sugon.entity.ToolsDemandPlanEntity;
import com.sugon.modules.sparepart.consts.SparePartNeedsPlanProgress;
import com.sugon.service.SysDeptService;
import com.sugon.service.ToolsDemandPlanService;
import com.sugon.utils.ShiroUtils;
import com.sugon.utils.excel.ExcelExport;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 备件需求计划Service实现类
 *
 * @author sugon
 * @date 2019-08-02 14:31:17
 */
@Service("toolsDemandPlanService")
public class ToolsDemandPlanServiceImpl implements ToolsDemandPlanService {

    @Autowired
    private ToolsDemandPlanDao toolsDemandPlanDao;
    @Autowired
    private ToolsDemandPlanItemDao toolsDemandPlanItemDao;
    @Autowired
    private SysDeptService deptService;

    /**
     * isExists
     *
     * @param userId
     * @param month  月份
     * @return
     */
    @Override
    public boolean isExists(String userId, String month) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("organId", userId);
        param.put("organMonth", month);
        return queryTotal(param) > 0;
    }

    /**
     * generateUniqueCode
     *
     * @param object
     * @return
     */
    @Override
    public String generateUniqueCode(Object object) {
        ToolsDemandPlanEntity toolsDemandPlan = (ToolsDemandPlanEntity) object;
        String planCode = toolsDemandPlan.getPlanCode();
        if (StrUtil.isEmpty(planCode)) {
            String workshop = ShiroUtils.getWorkshop();
            Assert.notNull(workshop, "只有处于某部门下的用户执行该操作！");
            // 设置备件需求计划编码
            SysDeptEntity deptEntity = deptService.queryObject(workshop);
            Assert.notNull(deptEntity, "非法所属部门编码！");
            planCode = deptEntity.getDcode() + "-" + toolsDemandPlan.getOrganMonth().replace("-", "");
        }
        String matchedMaxPlanCode = toolsDemandPlanDao.queryMatchedMaxPlanCode(planCode);
        if (StrUtil.isNotEmpty(matchedMaxPlanCode)) {
            planCode = com.sugon.modules.utils.StrUtil.increase(matchedMaxPlanCode, planCode + "-", 1, 1);
        }
        return planCode;
    }

    /**
     * queryObject
     *
     * @param id 主键
     * @return
     */
    @Override
    public ToolsDemandPlanEntity queryObject(String id) {
        return toolsDemandPlanDao.queryObject(id);
    }

    /**
     * queryObjectByCode
     *
     * @param code 需求
     * @return
     */
    @Override
    public ToolsDemandPlanEntity queryObjectByCode(String code) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("planCode", code);
        List<ToolsDemandPlanEntity> needsList = toolsDemandPlanDao.queryList(param);
        return CollectionUtil.isNotEmpty(needsList) ? needsList.get(0) : null;
    }

    /**
     * queryList
     *
     * @param map 参数
     * @return
     */
    @Override
    public List<ToolsDemandPlanEntity> queryList(Map<String, Object> map) {
        return toolsDemandPlanDao.queryList(map);
    }

    /**
     * queryTotal
     *
     * @param map 参数
     * @return
     */
    @Override
    public int queryTotal(Map<String, Object> map) {
        return toolsDemandPlanDao.queryTotal(map);
    }

    /**
     * save
     *
     * @param toolsDemandPlan 实体
     * @return
     */
    @Override
    public int save(ToolsDemandPlanEntity toolsDemandPlan) {
        toolsDemandPlan.setPlanCode(generateUniqueCode(toolsDemandPlan));
        // 设置编制人信息
        SysUserEntity user = ShiroUtils.getUserEntity();
        toolsDemandPlan.setApplyUnit(user.getDeptId());
        toolsDemandPlan.setOrganId(ShiroUtils.getWorkshop());
        toolsDemandPlan.setOrganUser(user.getUserId());
        toolsDemandPlan.setProgress(SparePartNeedsPlanProgress.NEW);
        // 设置基础信息
        toolsDemandPlan.setId(RandomUtil.randomString(32));
        toolsDemandPlan.setCreateTime(DateUtil.date());
        toolsDemandPlan.setCreateUser(user.getUserId());
        toolsDemandPlan.setDelFlag(1);
        // 默认未导出
        toolsDemandPlan.setIsExported(0);
        // 保存备件需求计划
        return toolsDemandPlanDao.save(toolsDemandPlan);
    }

    /**
     * update
     *
     * @param toolsDemandPlan 实体
     * @return
     */
    @Override
    public int update(ToolsDemandPlanEntity toolsDemandPlan) {
        toolsDemandPlan.setUpdateUser(ShiroUtils.getUserId());
        toolsDemandPlan.setUpdateDate(DateUtil.date());
        return toolsDemandPlanDao.update(toolsDemandPlan);
    }

    /**
     * delete
     *
     * @param id
     * @return
     */
    @Override
    public int delete(String id) {
        return toolsDemandPlanDao.delete(id);
    }

    /**
     * deleteBatch
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(String[] ids) {
        if (ArrayUtil.isEmpty(ids)) {
            return 0;
        }
        int num = 0;
        for (String requId : ids) {
            toolsDemandPlanItemDao.deleteByPlanId(requId);
            num += toolsDemandPlanDao.delete(requId);
        }
        return num;
    }

    /**
     * export
     *
     * @param params   业务参数
     * @param response 响应对象
     */
    @Override
    public void export(Map<String, Object> params, HttpServletResponse response) {
        // 根据需求计划ID查询所有明细
        String ids = MapUtil.getStr(params, "ids");
        String[] planIdArray = ids.split(",");
        if (ArrayUtil.isEmpty(planIdArray)) {
            return;
        }
        // 更新已导出状态
        for (String planId : planIdArray) {
            Map<String, Object> param = new HashMap<>(2);
            param.put("isExported", 1);
            param.put("id", planId);
            toolsDemandPlanDao.update(param);
        }

        List<Map<String, Object>> recordList = toolsDemandPlanDao.queryItemsByPlanIds(planIdArray);
        ExcelExport ee = new ExcelExport("需求计划明细");
        String[] header = new String[]{"计划编码", "需求车间", "提出人", "备件编码", "erp编码", "备件名称", "备件规格", "需求数量", "预计使用时间", "ABC类", "单价"};
        if (CollectionUtil.isNotEmpty(recordList)) {
            ee.addSheetByMap("需求计划明细", recordList, header);
            ee.export(response);
        }
    }
}
